import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import roc_curve, auc, accuracy_score
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import numpy as np

try:
    # 数据处理
    # 读取数据
    df = pd.read_excel('信用卡精准营销模型.xlsx')

    # 处理缺失值，这里简单填充为均值，可按需修改
    df = df.fillna(df.mean())

    # 提取特征变量和目标变量
    X = df.drop(columns='响应')
    y = df['响应']

    # 数据标准化
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)

    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=123)

    # 分析与建模
    # 模型训练及搭建
    clf = AdaBoostClassifier(random_state=123)
    clf.fit(X_train, y_train)

    # 使用交叉验证评估模型稳定性
    cv_scores = cross_val_score(clf, X_train, y_train, cv=5)
    print(f"交叉验证平均得分: {np.mean(cv_scores)}")

    # 超参数调优
    # 定义参数网格
    param_grid = {
        'n_estimators': [50, 100, 150],
        'learning_rate': [0.1, 0.5, 1.0]
    }

    # 创建网格搜索对象
    grid_search = GridSearchCV(AdaBoostClassifier(random_state=123), param_grid, cv=5)

    # 进行网格搜索
    grid_search.fit(X_train, y_train)

    # 输出最佳参数和最佳得分
    print("最佳参数:", grid_search.best_params_)
    print("最佳得分:", grid_search.best_score_)

    # 使用最佳参数的模型进行预测和评估
    best_clf = grid_search.best_estimator_
    y_pred = best_clf.predict(X_test)

    # 计算模型准确度评分
    accuracy = accuracy_score(y_test, y_pred)
    print(f"调优后模型的准确度评分: {accuracy}")

    # 查看预测属于各个分类的概率
    y_pred_proba = best_clf.predict_proba(X_test)
    # 这里假设类别为0和1，取预测为1的概率
    positive_proba = y_pred_proba[:, 1]

    # 绘制ROC曲线和计算AUC值
    fpr, tpr, thresholds = roc_curve(y_test, positive_proba)
    roc_auc = auc(fpr, tpr)
    plt.plot(fpr, tpr, label='ROC curve (area = %0.4f)' % roc_auc)
    plt.plot([0, 1], [0, 1], 'k--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver Operating Characteristic')
    plt.legend(loc="lower right")
    plt.show()
    print(f"调优后AUC值: {roc_auc}")

    # 分析特征重要性
    feature_importances = pd.DataFrame(best_clf.feature_importances_, index=X.columns, columns=['重要性'])
    feature_importances = feature_importances.sort_values(by='重要性', ascending=False)
    print(feature_importances)

except FileNotFoundError:
    print("错误：未找到 '信用卡精准营销模型.xlsx' 文件，请检查文件路径。")
except Exception as e:
    print(f"发生未知错误: {e}")

import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV, learning_curve
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import roc_curve, auc, accuracy_score, confusion_matrix
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import ConfusionMatrixDisplay

try:
    # 数据处理
    # 读取数据
    df = pd.read_excel('信用卡精准营销模型.xlsx')

    # 处理缺失值，这里简单填充为均值，可按需修改
    df = df.fillna(df.mean())

    # 提取特征变量和目标变量
    X = df.drop(columns='响应')
    y = df['响应']

    # 数据标准化
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)

    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=123)

    # 分析与建模
    # 模型训练及搭建
    clf = AdaBoostClassifier(random_state=123)
    clf.fit(X_train, y_train)

    # 使用交叉验证评估模型稳定性
    cv_scores = cross_val_score(clf, X_train, y_train, cv=5)
    print(f"交叉验证平均得分: {np.mean(cv_scores)}")

    # 超参数调优
    # 定义参数网格
    param_grid = {
        'n_estimators': [50, 100, 150],
        'learning_rate': [0.1, 0.5, 1.0]
    }

    # 创建网格搜索对象
    grid_search = GridSearchCV(AdaBoostClassifier(random_state=123), param_grid, cv=5)

    # 进行网格搜索
    grid_search.fit(X_train, y_train)

    # 输出最佳参数和最佳得分
    print("最佳参数:", grid_search.best_params_)
    print("最佳得分:", grid_search.best_score_)

    # 使用最佳参数的模型进行预测和评估
    best_clf = grid_search.best_estimator_
    y_pred = best_clf.predict(X_test)

    # 计算模型准确度评分
    accuracy = accuracy_score(y_test, y_pred)
    print(f"调优后模型的准确度评分: {accuracy}")

    # 查看预测属于各个分类的概率
    y_pred_proba = best_clf.predict_proba(X_test)
    # 这里假设类别为0和1，取预测为1的概率
    positive_proba = y_pred_proba[:, 1]

    # 绘制ROC曲线和计算AUC值
    fpr, tpr, thresholds = roc_curve(y_test, positive_proba)
    roc_auc = auc(fpr, tpr)
    plt.figure(figsize=(12, 8))
    plt.subplot(2, 2, 1)
    plt.plot(fpr, tpr, label='ROC curve (area = %0.4f)' % roc_auc)
    plt.plot([0, 1], [0, 1], 'k--')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Receiver Operating Characteristic')
    plt.legend(loc="lower right")

    # 绘制混淆矩阵
    cm = confusion_matrix(y_test, y_pred)
    disp = ConfusionMatrixDisplay(confusion_matrix=cm)
    plt.subplot(2, 2, 2)
    disp.plot(ax=plt.gca())
    plt.title('Confusion Matrix')

    # 绘制特征重要性柱状图
    feature_importances = pd.DataFrame(best_clf.feature_importances_, index=X.columns, columns=['重要性'])
    feature_importances = feature_importances.sort_values(by='重要性', ascending=False)
    plt.subplot(2, 2, 3)
    feature_importances.plot(kind='bar', ax=plt.gca())
    plt.title('Feature Importance')
    plt.xlabel('Features')
    plt.ylabel('Importance')

    # 绘制学习曲线
    train_sizes, train_scores, test_scores = learning_curve(
        best_clf, X_train, y_train, cv=5, n_jobs=-1,
        train_sizes=np.linspace(.1, 1.0, 5))
    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)
    plt.subplot(2, 2, 4)
    plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
                     train_scores_mean + train_scores_std, alpha=0.1,
                     color="r")
    plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
                     test_scores_mean + test_scores_std, alpha=0.1, color="g")
    plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
             label="Training score")
    plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
             label="Cross-validation score")
    plt.xlabel("Training examples")
    plt.ylabel("Score")
    plt.title('Learning Curve')
    plt.legend(loc="best")

    plt.tight_layout()
    plt.show()

    print(f"调优后AUC值: {roc_auc}")
    print(feature_importances)

except FileNotFoundError:
    print("错误：未找到 '信用卡精准营销模型.xlsx' 文件，请检查文件路径。")
except Exception as e:
    print(f"发生未知错误: {e}")
